﻿using System;
using System.Collections.Concurrent;
using Letter.IO.Buf;

namespace Beefly.Json.Buffer;

static class BufferManager
{
    static BufferManager()
    {
        Alloc();
    }

    private static ConcurrentQueue<IBuffer<char>> queue = new();

    private static void Alloc()
    {
        var count = (Environment.ProcessorCount * 2) * 32;
        for (int i = 0; i < count; i++)
        {
            queue.Enqueue(BufferProvider.Create<char>());
        }
    }

    public static IBuffer<char> Get()
    {
        if (queue.Count < 1)
        {
            Alloc();
        }

        queue.TryDequeue(out var buf);
        return buf;
    }

    public static void Ret(IBuffer<char> buf)
    {
        queue.Enqueue(buf);
    }
}